package impl

import (
	"context"
	"vblog/app/user"
	"vblog/conf"
	"vblog/exception"
	"vblog/ioc"

	"gorm.io/gorm"
)

// 做个约束，确保 UserServiceImpl 结构体确实实现了 user.Service 接口
var _ user.Service = &UserServiceImpl{}

type UserServiceImpl struct {
	db *gorm.DB
}

// 注册到ioc
func init() {
	ioc.Controller().RegistryIoc(&UserServiceImpl{})
}

// 初始化
func (u *UserServiceImpl) Init() {
	u.db = conf.C().Mysql.GetConn()

}

// 实现Name
func (u *UserServiceImpl) Name() string {
	return "user"
}

// func NewUserServiceImpl() *UserServiceImpl {
// 	return &UserServiceImpl{
// 		db: conf.C().Mysql.GetConn(),
// 	}

// }

func (i *UserServiceImpl) CreateUser(ctx context.Context, req *user.CreateUserRequest) (*user.User, error) {
	// 校验用户
	if err := req.Validate(); err != nil {
		return nil, err
	}

	// 创建User对象
	ins := user.NewUser(req)
	ins.PasswordHash()

	// 保存对象
	if err := i.db.WithContext(ctx).Create(ins).Error; err != nil {
		return nil, err
	}

	// 返回结果
	return ins, nil
}

func (i *UserServiceImpl) DescribeUser(ctx context.Context, req *user.DescribeUserRequest) (*user.User, error) {
	// 构造查询条件
	query := i.db.WithContext(ctx)
	switch req.DescribeBy {
	case user.DESCRIBEBY_ID:
		query = query.Where("id = ?", req.DescribeValue)
	case user.DESCRIBEBY_USERNAME:
		query = query.Where("username  = ?", req.DescribeValue)
	}

	// 查询语句
	ins := user.NewUser(user.NewCreateUserRequest())
	err := query.First(ins).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, exception.NewNotFound("用户 %s 未找到", req.DescribeValue)
		}
		return nil, err
	}

	return ins, nil
}

// 根据id删除用户（id是唯一标识，username不是）
func (i *UserServiceImpl) DeleteUser(ctx context.Context, req *user.DeleteUserRequest) error {
	// 先验证是否能查询到
	if _, err := i.DescribeUser(ctx, user.NewDescribeUserRequest_By_ID(req.ID)); err != nil {
		return err
	}

	// 删除用户
	ins := user.NewUser(user.NewCreateUserRequest())

	return i.db.WithContext(ctx).Where("id = ?", req.ID).Delete(ins).Error
}
